namespace Digitalmes.Application.Sys.Users.Queries;

/// <summary>
/// 分页查询用户命令。
/// </summary>
public record GetUserListWithPagedQuery(
    string? UserName,
    string? Realname,
    long? OrgId,
    int PageNumber,
    int PageSize) : IPagedQuery, IRequest<IResult<PagedList<SysUserDto>>>;

internal sealed class GetUserListWithPagedQueryHandler(IRepository<SysUser> repo) : IRequestHandler<GetUserListWithPagedQuery, IResult<PagedList<SysUserDto>>>
{
    public async Task<IResult<PagedList<SysUserDto>>> Handle(GetUserListWithPagedQuery request, CancellationToken cancellationToken)
    {
        var items = await repo.AsQueryable()
            .Includes(s => s.Org)
            .Includes(s => s.Pos)
            .Includes(m => m.UserRoles, it => it.Role)
            .WhereIF(!string.IsNullOrEmpty(request.UserName), m => m.Username == request.UserName)
            .WhereIF(!string.IsNullOrEmpty(request.Realname), m => m.Realname.Contains(request.Realname!))
            .WhereIF(request.OrgId > 0, m => m.OrgId == request.OrgId)
            .GetPagedListAsync(request.PageNumber, request.PageSize, cancellationToken);
        return Result.From(items.Adapt<PagedList<SysUserDto>>());
    }
}
